<template>
    <el-row>
        <el-col style="text-align: left;padding-bottom: 10px;">
            <el-button type="danger" size="small" @click="deleteAllBtnClick">删除选中</el-button>

            <el-button type="primary" size="small" @click="showAddAdForm">新增</el-button>

        </el-col>
    </el-row>

    <el-row>
        <el-col>
            <el-table border :data="tableList" @selection-change="selectRowsChange">
                <el-table-column type="selection"></el-table-column>


                <el-table-column label="图片" width="80">
                    <template #default="scope">
                        <el-image class="table-cover-image" :preview-src-list="[scope.row.cover]" :preview-teleported="true"
                            :src="scope.row.cover" lazy fit="contain"></el-image>
                    </template>
                </el-table-column>

                <el-table-column prop="name" label="显示文字" width="200" />

                <el-table-column prop="sort" label="排序值" width="150" />

                <el-table-column label="是否显示">
                    <template #default="scope">
                        <el-text v-if="scope.row.show_status == CommonCode.ON" class="mx-1" type="success">显示</el-text>
                        <el-text v-else type="info">不显示</el-text>
                    </template>
                </el-table-column>


                <!-- <el-table-column prop="jump_url" label="跳转地址" width="200" /> -->
                <el-table-column label="跳转">
                    <template #default="{ row }">
                        <div v-if="row.jump_method == AdCode.JUMP_METHOD_NONE || !row.jump_url">
                            <el-text type="info">无</el-text>
                        </div>
                        <div v-else>
                            <el-text type="success">{{ row.jump_method_text }}</el-text>

                            <div>
                                <el-tooltip :content="row.jump_url">
                                    <el-text line-clamp="1" truncate>{{ row.jump_url }}</el-text>
                                </el-tooltip>
                            </div>
                        </div>

                    </template>
                </el-table-column>

                <el-table-column label="操作" fixed="right">
                    <template #default="{ row }">
                        <el-button size="small" @click="showEditAdForm(row)">编辑</el-button>
                    </template>
                </el-table-column>
            </el-table>

        </el-col>
    </el-row>


    <!-- BEGIN 新增弹框 -->
    <el-dialog v-model="addAdForm.showDialog" :draggable="true" header="新增">
        <el-form ref="addAdFormRef" :model="addAdForm.formData" :rules="addAdForm.rules" label-width="auto">

            <el-form-item label="图片" prop="cover">
                <el-input type="hidden" name="cover" v-model="addAdForm.formData.cover"></el-input>
                <Upload :key="addAdForm.uuid" @on-success="addAdFormImgUploadSuccess"></Upload>
            </el-form-item>

            <el-form-item label="排序值" prop="sort">
                <el-input v-model="addAdForm.formData.sort" name="sort"></el-input>
            </el-form-item>

            <el-form-item label="文字" prop="name">
                <el-input v-model="addAdForm.formData.name" name="name"></el-input>
            </el-form-item>

            <el-form-item label="显示状态" prop="show_status">
                <el-switch v-model="addAdForm.formData.show_status" :active-value="CommonCode.SHOW"
                    :inactive-value="CommonCode.HIDE" />
            </el-form-item>

            <el-form-item label="跳转方式" prop="jump_method">
                <el-select v-model="addAdForm.formData.jump_method">
                    <el-option v-for="(text, val) in jumpMethodArr" :label="text" :value="val"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item v-if="addAdForm.formData.jump_method != AdCode.JUMP_METHOD_NONE" label="跳转链接" prop="jump_url">
                <el-input type="textarea" v-model="addAdForm.formData.jump_url" name="jump_url"></el-input>
            </el-form-item>

            <el-button :loading="addAdForm.onSubmiting" type="primary" @click="onAddSubmit(addAdFormRef)">提交</el-button>
        </el-form>
    </el-dialog>
    <!-- END 新增弹框  -->

    <!-- BEGIN 编辑弹框 -->
    <el-dialog v-model="editAdForm.showDialog" :draggable="true" header="新增">
        <el-form ref="editAdFormRef" :model="editAdForm.formData" :rules="editAdForm.rules" label-width="auto">

            <el-form-item label="图片" prop="cover">
                <el-input type="hidden" name="cover" v-model="editAdForm.formData.cover"></el-input>
                <Upload :key="editAdForm.uuid" @on-success="editAdFormImgUploadSuccess" v-model:file-list="editCover">
                </Upload>
            </el-form-item>

            <el-form-item label="排序值" prop="sort">
                <el-input v-model="editAdForm.formData.sort" name="sort"></el-input>
            </el-form-item>

            <el-form-item label="文字" prop="name">
                <el-input v-model="editAdForm.formData.name" name="name"></el-input>
            </el-form-item>

            <el-form-item label="显示状态" prop="show_status">
                <el-switch v-model="editAdForm.formData.show_status" :active-value="CommonCode.ON"
                    :inactive-value="CommonCode.OFF" />
            </el-form-item>

            <el-form-item label="跳转方式" prop="jump_method">
                <el-select v-model="editAdForm.formData.jump_method">
                    <el-option v-for="(text, val) in jumpMethodArr" :label="text" :value="val"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item v-if="editAdForm.formData.jump_method != AdCode.JUMP_METHOD_NONE" label="跳转链接" prop="jump_url">
                <el-input type="textarea" v-model="editAdForm.formData.jump_url" name="jump_url"></el-input>
            </el-form-item>

            <el-button :loading="editAdForm.onSubmiting" type="primary" @click="onEditSubmit(editAdFormRef)">提交</el-button>
        </el-form>
    </el-dialog>
    <!-- END 编辑弹框  -->
</template>

<script setup>
import Upload from '@/components/Upload.vue';

import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router';
import msgUtil from '@/utils/msgUtil'

import CommonCode from '@/constants/CommonCode'
import AdCode from '@/constants/AdCode'
import arr from '@/utils/arr'
import str from '@/utils/str'


import adApi from '@/api/ad';

const route = useRoute();

// 分组id
var groupId = '';

onMounted(() => {

    groupId = route.query.groupId;
    loadAd();
})

function loadAd() {
    adApi.allAd({
        group_id: groupId
    })
        .then((res) => {
            msgUtil.alertIfError(res).then(() => {
                res.data.lists.forEach((item) => {
                    item.jump_method_text = AdCode.textOfJumpMethod(item.jump_method)
                })
                tableList.value = res.data.lists;
            })
        })
}

const tableList = ref([])


// 多选
// 选中的table数据
const selectedIds = ref([]);

// 选中的行数据
function selectRowsChange(rows) {
    let ids = arr.pluck(rows, 'id');
    selectedIds.value = ids
}
// 点击删除所有
function deleteAllBtnClick() {
    if (selectedIds.value.length === 0) {
        msgUtil.warnMsg({
            message: '请先选择',
        });
        return;
    }
    adApi.delAd(selectedIds.value).then(res => {
        msgUtil.handleApiRes(res, {
            onApiSuccess() {
                loadAd();
            }
        })
    })
}


const jumpMethodArr = AdCode.textOfJumpMethod();


// 新增
const addAdFormRef = ref();

const addAdForm = ref({
    showDialog: false,
    onSubmiting: false,
    formData: {},
    uuid : '',
    rules: {
        cover: [
            { required: true, message: '请选择图片', type: 'url' }
        ],
        sort: [
            {
                required: true, message: '整数>=0',
                trigger: 'blur',
                validator(rule, value, callback) {

                    if (str.isNaturalNumber(value)) {
                        callback()
                    } else {
                        callback(new Error('必须是自然数,0,1,2...'))
                    }
                }
            }
        ],
        jump_url: [
            {
                validator(rule, value, cb) {
                    if (addAdForm.value.formData.jump_method == AdCode.JUMP_METHOD_OUT_LINK) {
                        if (str.isUrl(value)) {
                            cb()
                        } else {
                            cb(new Error('url格式不正确'))
                        }
                    } else {
                        cb()
                    }
                }
            }
        ]
    }
})

function showAddAdForm() {
    addAdForm.value.formData = {
        group_id: groupId,
        sort: 0,
        show_status: CommonCode.ON,
        cover: '',
        name: '',
        jump_method: AdCode.JUMP_METHOD_NONE,
        jump_url: '',
    }
    addAdForm.value.uuid = str.now()
    addAdForm.value.showDialog = true
}

function addAdFormImgUploadSuccess(res) {
    addAdForm.value.formData.cover = res.url
}

function onAddSubmit(formEl) {
    formEl.validate((valid, fields) => {
        if (!valid) {
            return;
        }
        if (addAdForm.value.onSubmiting) {
            return;
        }
        addAdForm.value.onSubmiting = true;
        adApi.addAd(addAdForm.value.formData)
            .then(res => {
                msgUtil.handleApiRes(res, {
                    onApiSuccess() {
                        addAdForm.value.showDialog = false
                        loadAd()
                    }
                })
            })
            .finally(() => {
                addAdForm.value.onSubmiting = false;
            })
    })
}

// 编辑
const editAdFormRef = ref();

const editAdForm = ref({
    showDialog: false,
    onSubmiting: false,
    uuid : '',
    formData: {},
    rules: {
        cover: [
            { required: true, message: '请选择图片', type: 'url' }
        ],
        sort: [
            {
                required: true, message: '整数>=0',
                trigger: 'blur',
                validator(rule, value, callback) {

                    if (str.isNaturalNumber(value)) {
                        callback()
                    } else {
                        callback(new Error('必须是自然数,0,1,2...'))
                    }
                }
            }
        ],
        jump_url: [
            {
                validator(rule, value, cb) {
                    if (editAdForm.value.formData.jump_method == AdCode.JUMP_METHOD_OUT_LINK) {
                        if (str.isUrl(value)) {
                            cb()
                        } else {
                            cb(new Error('url格式不正确'))
                        }
                    } else {
                        cb()
                    }
                }
            }
        ]
    }
})

const editCover = ref([]);

// const editAdUploadRef = ref();

function showEditAdForm(row) {
    row.jump_method = '' + row.jump_method
    row.show_status = '' + row.show_status

    arr.coverFieldType(row, { type: 'string' })
    // upload组件内的预览图片没有更新
    // setTimeout(() => {
        // editAdUploadRef.value.updatePreviewFileList([
        //     {
        //         name: row.cover,
        //         url: row.cover,
        //     }
        // ])
    // },50)

    editCover.value = [
            {
                name: row.cover,
                url: row.cover,
            }
        ]
    editAdForm.value.uuid = str.now()
    editAdForm.value.formData = { ...row };
    editAdForm.value.showDialog = true
}

function editAdFormImgUploadSuccess(res) {
    editAdForm.value.formData.cover = res.url
}

function onEditSubmit(formEl) {
    formEl.validate((valid, fields) => {
        if (!valid) {
            return;
        }
        if (editAdForm.value.onSubmiting) {
            return;
        }
        editAdForm.value.onSubmiting = true;
        adApi.updateAd(editAdForm.value.formData)
            .then(res => {
                msgUtil.handleApiRes(res, {
                    onApiSuccess() {
                        editAdForm.value.showDialog = false
                        loadAd()
                    }
                })
            })
            .finally(() => {
                editAdForm.value.onSubmiting = false;
            })
    })
}

</script>